package com.yxq.mdt.app.modules.bottomsheet;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.blankj.utilcode.util.ToastUtils;
import com.google.android.material.bottomsheet.BottomSheetDialogFragment;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yxq.mdt.app.R;
import com.yxq.mdt.app.dialog.CostumerDialog;
import com.yxq.mdt.app.modules.bean.UploadImageBean;
import com.yxq.mdt.app.modules.publish.ui.bean.PublishListBean;
import com.yxq.mdt.app.modules.socialcontact.adapter.CommentListAdapter;
import com.yxq.mdt.app.modules.socialcontact.bean.AddCommentBean;
import com.yxq.mdt.app.modules.socialcontact.bean.AddCommentNoImgBean;
import com.yxq.mdt.app.modules.socialcontact.bean.FileList;
import com.yxq.mdt.app.modules.socialcontact.bean.NewAddCommentBean;
import com.yxq.mdt.app.modules.socialcontact.bean.TopicComment;
import com.yxq.mdt.app.modules.socialcontact.bean.gsTopicComment;
import com.yxq.mdt.app.modules.socialcontact.model.MainSocialContactModel;
import com.yxq.mdt.app.modules.socialcontact.ui.fragment.SocialStateCommentFragment;
import com.yxq.mdt.app.net.ApiModel;
import com.yxq.mdt.app.utils.GlideEngine;
import com.yxq.mdt.app.utils.GridSpacingItemDecoration;
import com.yxq.mdt.app.widgets.OssHelper;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import io.reactivex.Observable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

import static android.app.Activity.RESULT_OK;

/**
 * @author L
 * @time
 * @describe 评论动态弹出框
 */
public class CommentBottomSheetDialog extends BottomSheetDialogFragment {
    Unbinder unbinder;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.comment_add_exit)
    EditText commentAddExit;
    @BindView(R.id.comment_add_img)
    ImageView commentAddImg;
    @BindView(R.id.comment_add_send)
    TextView commentAddSend;
    String topicId, replyId;
    CommentListAdapter uploadImageListAdapter;
    List<UploadImageBean> uploadImageBeanList;
    List<LocalMedia> images;
    int imageNumberSize = 0;
    List<String> imageList;
    int len = 0, type;
    List<FileList> lists;
    SocialStateCommentFragment socialStateCommentFragment;
    private CostumerDialog mLoadingDialog;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //设置背景透明，才能显示出layout中诸如圆角的布局，否则会有白色底（框）
        setStyle(BottomSheetDialogFragment.STYLE_NORMAL, R.style.CustomBottomSheetDialogNoTheme);
    }

    public CommentBottomSheetDialog(SocialStateCommentFragment socialStateCommentFragment, String topicId, String replyId, int type) {
        this.topicId = topicId;
        this.replyId = replyId;
        this.type = type;
        this.socialStateCommentFragment = socialStateCommentFragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.comment_two_bottom_dialog, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;

    }

    private void initView() {
        if (TextUtils.isEmpty(replyId)) {
            commentAddImg.setVisibility(View.VISIBLE);
            recyclerView.setVisibility(View.VISIBLE);
        } else {
            recyclerView.setVisibility(View.GONE);
            commentAddImg.setVisibility(View.GONE);
        }
        //图片
        uploadImageBeanList = new ArrayList<>();

        imageList = new ArrayList<>();
        lists = new ArrayList<>();

        uploadImageListAdapter = new CommentListAdapter(uploadImageBeanList);
        recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 3));
        recyclerView.setAdapter(uploadImageListAdapter);
        recyclerView.addItemDecoration(new GridSpacingItemDecoration(3, 5, false));
        uploadImageListAdapter.setOnItemClickListener((adapter, view, position) -> {
            imageNumberSize = position;
            if (uploadImageListAdapter.getItem(position).getItemType() == -1) {
                selectImages();
            } else {
                //预览图片
                PictureSelector.create(getActivity()).externalPicturePreview(position, images,1);
            }
        });
        uploadImageListAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            List<UploadImageBean> uploadImageBeanList = uploadImageListAdapter.getData();
            if (uploadImageBeanList.get(uploadImageBeanList.size() - 1).getItemType() != -1) {
                uploadImageBeanList.remove(position);
                //第一张不是添加图片，添加按钮
                List<UploadImageBean> temp = new ArrayList<>();
                temp.addAll(uploadImageBeanList);
                temp.add(new UploadImageBean());
                uploadImageListAdapter.setNewData(temp);
            } else {
                uploadImageListAdapter.remove(position);
                uploadImageBeanList.clear();
                images.clear();
                commentAddImg.setVisibility(View.VISIBLE);
            }
        });
        commentAddImg.setOnClickListener(view -> selectImages());

        commentAddSend.setOnClickListener(view -> {
            if (uploadImageListAdapter != null && uploadImageListAdapter.getData().size() != 0) {
                //上传图片
                uploadImageAli();
            } else {
                //无图片
                if (TextUtils.isEmpty(replyId)) {
                    //评论动态
                    AddCommentNoImgBean addCommentNoImgBean = new AddCommentNoImgBean();
                    gsTopicComment gsTopicComment = new gsTopicComment(commentAddExit.getText().toString(), topicId, type);
                    addCommentNoImgBean.setGsTopicComment(gsTopicComment);
                    sendComment(JSON.toJSONString(addCommentNoImgBean));
                } else {
                    //回复评论
                    NewAddCommentBean addCommentBean = new NewAddCommentBean();
                    TopicComment gsTopicComment = new TopicComment(commentAddExit.getText().toString(), topicId, replyId, type);
                    addCommentBean.setGsTopicComment(gsTopicComment);
                    sendComment(JSON.toJSONString(addCommentBean));
                }
            }
        });
    }


    /**
     * 打开图片选择器
     */
    private void selectImages() {
        //相册
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .maxSelectNum(1)//最大选择数目 最大6张减去现在已经添加的张数
                .compress(true)
                .minSelectNum(1)
                .imageSpanCount(4)
                .selectionMode(PictureConfig.MULTIPLE)
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    /**
     * 上传图片到阿里云
     */
    @SuppressLint({"AutoDispose", "CheckResult"})
    private void uploadImageAli() {
        if (images != null && images.size() != 0) {
            showLoadingDialog();
            imageList.clear();
            len = 0;
            Observable.fromIterable(images)
                    .observeOn(Schedulers.io())
                    .map(localMedia -> {
                        File file = new File(localMedia.getCompressPath());
                        OssHelper.getOss(getActivity(), true).putObject(OssHelper.getPutObjectRequest(OssHelper.GS_APP_VOICE + file.getName(), file.getPath()));
                        return OssHelper.getOssPrefixUrl(OssHelper.GS_APP_VOICE, file.getName());
                    })
                    .subscribe(s -> {
                        if (!TextUtils.isEmpty(s)) {
                            if (s != null) {
                                len++;
                            }
                            imageList.add(s);
                            //图片
                            FileList FileList = new FileList(s);
                            lists.add(FileList);

                            if (len == images.size()) {
                                AddCommentBean addCommentBean = new AddCommentBean();
                                //发布评论内容
                                gsTopicComment gsTopicComment = new gsTopicComment(commentAddExit.getText().toString(), topicId, type);
                                addCommentBean.setGsTopicComment(gsTopicComment);

                                //图片参数
                                addCommentBean.setFileList(lists);
                                sendComment(JSON.toJSONString(addCommentBean));
                            }
                        }
                    }, throwable -> {
                    });
        }
    }

    /**
     * 发表评论或者回复
     *
     * @param data
     */
    private void sendComment(String data) {
        final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(JSON, data);
        MainSocialContactModel.setComment(body, new ApiModel.CommonCallback<PublishListBean>() {
            @Override
            public void onSuccess(PublishListBean addCommentBean) {
                if (socialStateCommentFragment != null) {
                    socialStateCommentFragment.initData();
                }
                hideLoadingDialog();
                ToastUtils.showShort("评论成功");
                dismiss();
            }

            @Override
            public void onError(String errMsg) {
                hideLoadingDialog();
                ToastUtils.showShort(errMsg);
                dismiss();
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    images = PictureSelector.obtainMultipleResult(data);
                    if (images.size() > 0) {
                        commentAddImg.setVisibility(View.GONE);
                    }
                    parseLocalMedia(images);
                    break;
                default:
                    throw new IllegalStateException("Unexpected value: " + requestCode);
            }
        }

        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 填充图片到界面
     *
     * @param images
     */
    private void parseLocalMedia(List<LocalMedia> images) {
        List<UploadImageBean> data = new ArrayList<>();
        UploadImageBean uploadImageBean;
        for (LocalMedia localMedia : images) {
            uploadImageBean = new UploadImageBean();
            uploadImageBean.setItemType(0);
            uploadImageBean.setPath(localMedia.getCompressPath());
            data.add(uploadImageBean);
        }
        List<UploadImageBean> temp = uploadImageListAdapter.getData();
        temp.addAll(data);
        temp.add(new UploadImageBean());
        uploadImageListAdapter.setNewData(temp);

        if (uploadImageListAdapter.getData().size() == 10) {
            uploadImageListAdapter.getData().remove(9);
        }
        uploadImageListAdapter.notifyDataSetChanged();
    }


    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        super.onDismiss(dialog);
        InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// 隐藏软键盘
        imm.hideSoftInputFromWindow(getActivity().getWindow().getDecorView().getWindowToken(), 0);
    }

    public void showLoadingDialog() {
        if (mLoadingDialog == null) {
            mLoadingDialog = new CostumerDialog.Builder(getActivity(), R.style.custom_dialog_no_match)
                    .setContentView(R.layout.dialog_common_loading_layout)
                    .setCancelable(true)
                    .create();
        }
        if (!mLoadingDialog.isShowing()) {
            mLoadingDialog.show();
        }
    }

    public boolean isDialogShowing() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            return true;
        } else {
            return false;
        }
    }

    public void hideLoadingDialog() {
        if (mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }
}
